<template>
  <view>
    <u-upload 
      ref="uUpload"
      :action="ossHost"
      :form-data="currentOssData"
      :file-list="fileList"
      :autoUpload="true"
      :before-upload="beforeUpload"
      :max-count="10"
      @on-remove="onRemove"
      @on-success="onSuccess" /> 
    <w-compress ref='wCompress' />
  </view>
</template>

<script>
import axios from '@/service'
import WCompress from '@/components/w-compress/w-compress.vue'
export default {
		data() {
			return {
        ossHost: '', // action上传的地址
        fileList: [], // 文件的图片列表 
        currentOssData: {} // 上传oss需要的参数
			}
		},
    components: {
      WCompress 
    },
    props: {
      serviceUrl: {
        type: String,
        default: ''
      },
      ossUrlKey: {
        type: String,
        default: ''
      },
      delImgUrl: {
        type: String,
        default: ''
      },
      maxNum: {
        type: Number,
        default: 20
      }
    },
    methods: {
      async beforeUpload (index,list) {
        let obj = null
        // 1 获取签名信息
        await axios.request({
          url: this.serviceUrl, method: 'get', params:{}
        }).then(({data}) => {
          this.ossHost = data.host ? 'http://' + data.host : ''
          obj = data
        })
        // 2 压缩图片
        await this.$refs.wCompress.start(list[index].file.path, {
          quality: 0.3,     // 压缩质量，默认0.8
        }).then(res => {
          console.log(res,'压缩后图片')
          // 3 转换需要的oss参数
          this.currentOssData = this.buildOssData(obj, res)
        })
        .catch(e => {
          console.log(e)
        })
      },
      onSuccess(data, index, lists, name) {
        const { key } = this.currentOssData
        const { file } = lists[index]
        let arrItem = {
          key: key,
          url: file.path
        }
        this.fileList.push(arrItem)
        this.currentOssData = {}
      },
      onRemove(index, lists, name) {
        let removeItem = this.fileList.splice(index,1)
        axios.request({
          url: this.delImgUrl,
          data: {key: removeItem[0].key, type: 'blicUrlA'}
        })
      },
      buildOssData ({
        policy = '',
        accessid = '',
        success_action_status = 200,
        signature = '',
        ...data
      }, file) {
        return {
          key: `${data[this.ossUrlKey]}/${this.getRandomKey(file)}`,
          policy,
          OSSAccessKeyId: accessid,
          success_action_status,
          signature
        }
      },
      getRandomKey (file) {
        let s = []
        let hexDigits = "0123456789abcdef"
        for (let i = 0; i < 36; i++) {
          s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
        }
        s[14] = "4"
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1)
        s[8] = s[13] = s[18] = s[23]
        let uuid = s.join("")
        let pos = file.lastIndexOf(".")
        let suffix = ""
        if (pos != -1) {
          suffix = file.substring(pos)
        }
        console.log(`${uuid}${suffix}`)
        return `${uuid}${suffix}`
      }
    }
	}
</script>

<style>

</style>